package com.atguigu.gulimall.order.test;

import java.util.Scanner;

public class StackDemo {
    public static void main(String[] args) {
        ArrayStockDemo arrayStockDemo = new ArrayStockDemo(5);
        String kye = "";
        boolean b = true;
        Scanner scanner = new Scanner(System.in);
        while (b){
            System.out.println("show:表示显示栈");
            System.out.println("push:表示入栈");
            System.out.println("pop:表示取栈");
            System.out.println("exit:突出程序");
            kye = scanner.next();
            switch (kye){
                case "show":
                    arrayStockDemo.list();
                    break;
                case "push":
                    System.out.println("输出一个数：");
                    int value = scanner.nextInt();
                    arrayStockDemo.pushStock(value);
                    break;
                case "pop":
                    try {
                        int pop = arrayStockDemo.pop();
                        System.out.println("出栈的数据为："+pop);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    scanner.close();
                    b=false;
                    break;
            }
        }
    }
}

  class  ArrayStockDemo {
      private int maxSize;//数组最大值
      private int[] stock;//数组
      private int top=-1;//栈内的个数


      public ArrayStockDemo(int maxSize){
          this.maxSize = maxSize;
          stock = new int[this.maxSize];
      }
      /**
       * 判断是否为空
       *
       * @return
       */
      public boolean isEmty() {
          return top == -1;
      }

      /**
       * 判断栈是否已满
       */
      public boolean isMan(){
          return top == maxSize-1;
      }
      /**
       *入栈
       */
      public void pushStock(int value){
          //判断栈是否满了
          boolean man = isMan();
          if (man){
              System.out.println("栈已满");
          }else {
              top++;
              stock[top] = value;
          }
      }
      /**
       * 出栈
       */
      public int pop(){
          //判断栈内是否有数据
          boolean emty = isEmty();
          if (emty){
              throw new RuntimeException("栈空 没有数据");
          }else {
              int value = stock[top];
              top--;
              return value;
          }
      }
      /**
       * 遍历栈
       */
      public void list(){
          //判断栈是否为空
          boolean emty = isEmty();
          if (emty){
              System.out.println("栈空");
          }
          for (int i=top;i>=0;i--){
              System.out.printf("stock[%d]=%d\n",i,stock[i]);
              if (i==0){
                  return;
              }
          }
      }
  }

